import { CodecType } from "./codec"

export namespace type {

    export const ACK = 0;
    export const PING = 1;
    export const PONG = 2;
    export const SIMPLE_REQ = 3;
    export const SIMPLE_RES = 4;
    export const SESSION = 5;
    export const REQ = 6;
    export const RES = 7;
    export const NOTIFY = 8;
    export const NOTIFY_ACK = 9;

}


export namespace frame {
    export const HEAD = 0xE11E;
    export const END = 0xEF;
    export const HEAD0 = 0xE1;
    export const HEAD1 = 0x1E;
}

export namespace cmd {
    export const STATUS = 0x00;
    export const LOG = 0x01;
    export const OTA_START = 0x02;
    export const OTA_TRANSLATE = 0x03;
    export const OTA_COMPLETE = 0x04;
}


export function make(type: number, seq: number, ts: CodecType[]) {
    let size = 7;
    for (const v of ts) {
        size += v.size();
    }
    if (size > 255) {
        throw `size over ${size}`;
    }

    let buf = new Array<number>(size);

    buf[0] = frame.HEAD0;
    buf[1] = frame.HEAD1;
    buf[2] = size;
    buf[3] = type;
    buf[4] = seq;

    let index = 5;
    for (const v of ts) {
        v.encode(buf, index);
        index += v.size();
    }

    let s = 0;
    for (let i = 3; i < index; i++) {
        s = s ^ buf[i];
    }
    buf[index] = s;
    buf[index + 1] = frame.END;

    return buf;
}

